<template>
  <div ref="divContainer">
    <el-input v-model="filterText"
              prefix-icon="el-icon-search"
              placeholder="筛选"
              clearable size="small" style="margin-bottom: 5px;"
              maxlength="30"></el-input>
    <el-scrollbar ref="scroll"
                  :style="{ height: domHeight + 'px'}">
      <el-tree :data="this.tableList" lazy :load="handleLazyLoad"
               :props="this.tableListProps" :filter-node-method="filterNode"
               node-key="id"
               ref="tableList"
               @current-change="currentChangeHandler"
               :check-on-click-node="true"
               :default-expand-all="false"
               :highlight-current="true">
        <div class="custom-tree-node" slot-scope="{ node, data }">
          <span class="node-icon">
            <svg-icon icon-class="icon-datasource" v-if="node.level===2"></svg-icon>
            <svg-icon icon-class="icon-table" v-else-if="node.level>2"></svg-icon>
            <svg-icon icon-class="icon-opened" v-else-if="node.expanded"></svg-icon>
            <svg-icon icon-class="icon-closed" v-else="!node.expanded"></svg-icon>
          </span>
          <span>
            {{
              data.type === '1' ? (data.remark === data.name ? data.remark : data.remark + '(' + data.name + ')') : data.remark
            }}
          </span>
        </div>
      </el-tree>
    </el-scrollbar>
  </div>
</template>

<script>

export default {
  props: {},
  components: {},
  data() {
    return {
      domHeight: 360,
      filterText: '',
      flinkDataList: [],
      tableList: [],
      tableListProps: {
        label: 'name',
        children: 'children',
        isLeaf: 'isLeaf'
      }
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tableList.filter(val)
    }
  },
  mounted() {
    this.$nextTick(function () {
      var heightCss = window.getComputedStyle(this.$refs.divContainer).height
      if (heightCss === 'auto') {
        this.domHeight = document.documentElement['clientHeight'] - 226
      }
    })
  },
  computed: {},
  created() {
    this.init()
  },
  methods: {
    init() {
      let vFlinkDataBasePostData = {
        "page": 1,
        "pageSize": 99,
        "filters": {
          "name": "",
          "type": "",
          "groupName": "",
          "status": "",
          "enabled": ""
        },
        "sorts": []
      }
      this.filterText = ''
      this.$http({
        url: this.$http.adornFlinkUrl(`/database/page`),
        method: 'post',
        data: this.$http.adornData(vFlinkDataBasePostData)
      }).then(({data}) => {
        if (data && (data.code === 0 || data.code === 200)) {
          this.flinkDataList = this.flinkDataToTreeData(data)
          this.tableList = this.flinkDataList
        } else {
          this.tableList = []
        }
      })
    },
    flinkDataToTreeData(data) {
      let dataList = []
      let temp = {
        checked: null,
        id: "261462d117924f43995b32c1d5d299e3",
        name: "基础数据库",
        open: null,
        parentId: "0",
        remark: "基础数据库",
        type: null
      }
      // 组织数据源分组
      let group = []
      for (const item of data.data.list) {
        if (group === null || group.length <= 0) {
          group.push(item.groupName)
          continue
        }
        let index = group.findIndex((value, index) => value === item.groupName )
        if (index < 0) {
          group.push(item.groupName)
        }
      }
      // 组织子集
      for (let i = 0; i < group.length; i++) {
        let lGroupChildList = []
        for (const item of data.data.list) {
          if (item.groupName === group[i]) {
            lGroupChildList.push({
              checked: null,
              _level: 1,
              id: item.id,
              name: item.name,
              open: null,
              parentId: "0_"+i,
              remark: item.name,
              type: item.type
            })
          }
        }
        let lGroupData = {
          checked: null,
          _level: 0,
          id: "0_"+i,
          name: group[i],
          open: null,
          parentId: "0",
          remark: group[i],
          type: null,
          children: lGroupChildList
        }
        //
        dataList.push(lGroupData)
      }
      // 返回值
      return dataList
    },
    getDatasource (resolve) {

    },
    handleLazyLoad (node, resolve) {
      switch (node.level) {
        case 0:
          this.getDatasource(resolve)
          return
        case 1:
          return resolve(node.data.children)
        case 2:
          this.getTableList(node.data.id, resolve,node)
          return
      }
      return resolve([])
    },
    getTableList (id, resolve,parentNode) {
      let lDataBaseName = parentNode.data.name
      this.$http({
        url: this.$http.adornFlinkUrl(`/database/getSchemasAndTables`),
        method: 'get',
        params: this.$http.adornParams({
          id: id
        }, false)
      }).then(({data}) => {
        if (data && data.code === 200) {
          let list = []
          for (const item of data.data[0].tables) {
            list.push({
              label: item.name,
              dataBaseName: lDataBaseName,
              _level: 2,
              checked: null,
              id: item.name,
              comment: item.comment,
              name: item.name,
              open: null,
              parentId: id,
              remark: item.name,
              type: '1',
              schema: item.schema,
              schemaTableName: item.schemaTableName,
              schemaTableNameWithUnderline: item.schemaTableNameWithUnderline,
              isLeaf: true
            })
          }
          resolve(list)
        } else {
          resolve([])
          this.$message.error(data.message)
        }
      })
    },
    /***
     * 外部设置过滤
     * @text
     */
    filter(text) {
      this.filterText = text
    },
    currentChangeHandler(data, node) {
      if (node.level === 2) {
        this.$emit('srcSelectHandler', data)
      } else if (node.level === 3) {
        // 选择表节点，调用父组件函数
        this.$emit('tableSelectHandler', data, node)
      }
    },
    /***
     * 根据节点ID获取节点名称
     * @param id
     */
    getName(id) {
      var node = this.$refs.tableList.getNode(id)
      if (node) {
        this.$refs.tableList.setCurrentKey(id)
        return node.data.name
      }
      return ''
    },
    /***
     * 树节点过滤
     */
    filterNode(value, data) {
      if (!value) return true
      var values = []
      if (value.indexOf(',') > -1) {
        value = value.toLowerCase()
        values = value.split(',')
      } else {
        values.push(value)
      }
      for (var i = 0; i < values.length; i++) {
        if (data.name.toLowerCase().indexOf(values[i]) !== -1 || data.remark.toUpperCase().indexOf(values[i]) !== -1) {
          return true
        }
      }
    }
    // method end //////////////////////
  }
}
</script>

<style scoped>

</style>
